import logging

"""
注意不能在项目中其他地方再 import logging 了，否则会导致自定义在 tortoise 中失效
"""

class LogFormatter(logging.Formatter):
    RED = '\x1b[31m'
    GREEN = '\x1b[32m'
    YELLOW = '\x1b[33m'
    BLUE = '\x1b[34m'
    MAGENTA = '\x1b[35m'
    CYAN = '\x1b[36m'
    LIGHT_GRAY = '\x1b[37m'  # 灰色
    LIGHT_BLUE = '\x1b[94m'  # 浅蓝色
    ORANGE = '\x1b[38;5;202m'  # 橙色
    PURPLE = '\x1b[38;5;141m'  # 紫色
    PINK = '\x1b[38;5;206m'  # 粉红色
    RESET = '\x1b[0m'

    FORMATS = {
        logging.DEBUG: f"{LIGHT_BLUE}%(levelname)s{RESET}:    {PURPLE}[%(name)s]{RESET} | {GREEN}[%(asctime)s]{RESET} | {PINK}%(message)s{RESET}",
        logging.INFO: f"{GREEN}%(levelname)s{RESET}:     {PURPLE}[%(name)s]{RESET} | {GREEN}[%(asctime)s]{RESET} | {LIGHT_GRAY}%(message)s{RESET}",
        logging.WARNING: f"{YELLOW}%(levelname)s{RESET}:  {PURPLE}[%(name)s]{RESET} | {GREEN}[%(asctime)s]{RESET} | {YELLOW}%(message)s{RESET}",
        logging.ERROR: f"{RED}%(levelname)s{RESET}:    {PURPLE}[%(name)s]{RESET} | {GREEN}[%(asctime)s]{RESET} | {RED}%(message)s{RESET}",
        logging.CRITICAL: f"{RED}%(levelname)s{RESET}: {PURPLE}[%(name)s]{RESET} | {GREEN}[%(asctime)s]{RESET} | {MAGENTA}%(message)s{RESET}",
    }

    def format(self, record):
        log_fmt = self.FORMATS.get(record.levelno)
        formatter = logging.Formatter(log_fmt)
        return formatter.format(record)

def setup_logger(logger_name: str):
    logger = logging.getLogger(logger_name)
    logger.setLevel(logging.DEBUG)

    ch = logging.StreamHandler()
    ch.setLevel(logging.DEBUG)

    formatter = LogFormatter('%(levelname)s:\t  %(name)s | %(asctime)s | %(message)s')
    ch.setFormatter(formatter)

    logger.addHandler(ch)

    return logger

# Setup the logger
logger = setup_logger('helloyt-logger')

class Log:
    @staticmethod
    def debug(message, *args):
        context = ' | '.join(str(arg) for arg in args)
        full_message = f"{message}:\n{context}".strip()
        logger.debug(full_message)

    @staticmethod
    def info(message, *args):
        context = ' | '.join(str(arg) for arg in args)
        full_message = f"{message}:\n{context}".strip()
        logger.info(full_message)

    @staticmethod
    def warning(message, *args):
        context = ' | '.join(str(arg) for arg in args)
        full_message = f"{message}:\n{context}".strip()
        logger.warning(full_message)

    @staticmethod
    def error(message, *args):
        context = ' | '.join(str(arg) for arg in args)
        full_message = f"{message}:\n{context}".strip()
        logger.exception(full_message)
